package com.freesky.provider.image.controller;

import com.freesky.common.pojo.KindEditorResult;
import com.freesky.common.utils.reponse.JSONResponse;
import com.freesky.common.utils.reponse.JSONResponseDiretor;
import com.freesky.provider.image.util.UploadUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@Controller
public class ImageComtroller {
    @Value("${image.base-url}")
    private String imageBaseUrl;
    @Value("${image.save-path}")
    private String imageSavePath;

    @ResponseBody
    @RequestMapping(value = "/image/imageUpload", method = RequestMethod.POST,produces = {MediaType.APPLICATION_JSON_UTF8_VALUE}, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public JSONResponse uploadFile(@RequestPart("file") MultipartFile files) {

        String fileUrl = "";
        try {
            String fileName = files.getOriginalFilename();
            fileUrl = UploadUtil.save( files.getInputStream(), imageBaseUrl, imageSavePath,fileName);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return JSONResponseDiretor.buildSuccessJSONResponse(fileUrl);
    }
    @ResponseBody
    @PostMapping(value = "/kindeditor/imageUpload",produces = {MediaType.APPLICATION_JSON_UTF8_VALUE}, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public KindEditorResult kindEditor(@RequestPart("imgFile") MultipartFile files) {
        KindEditorResult kindEditorResult = new KindEditorResult();
        String fileUrl = "";
        try {
            String fileName = files.getOriginalFilename();
            fileUrl = UploadUtil.save( files.getInputStream(), imageBaseUrl, imageSavePath,fileName);
            kindEditorResult.setError(0);
            kindEditorResult.setUrl(fileUrl);
            return kindEditorResult;
        } catch (IOException e) {
            kindEditorResult.setError(1);
            kindEditorResult.setMessage("上传失败");
            e.printStackTrace();
        }
        return kindEditorResult;
    }

}
